package com.ln.lnzw.activity;

import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.ln.lnzw.R;
import com.ln.lnzw.adapter.ServerSubFeileiAdapter;
import com.ln.lnzw.adapter.ServerSubscribeTopAdapter;
import com.ln.lnzw.app.AppConstant;
import com.ln.lnzw.base.BaseActivity;
import com.ln.lnzw.bean.CategoryBean;
import com.ln.lnzw.bean.ServerSubscribeRecomBean;
import com.ln.lnzw.bean.ServerSubscribeRecomNetBean;
import com.ln.lnzw.bean.ServiceCategoryBean;
import com.ln.lnzw.bean.UniversalBean;
import com.ln.lnzw.event.SubscribeChangeEvent;
import com.ln.lnzw.net.HttpMethods;
import com.ln.lnzw.utils.ToastFactory;
import com.ln.lnzw.view.SpaceItemDecoration;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 作者 : wlt
 * 创建时间:  2018-04-25
 * QQ : 1346947404
 * 邮箱:wanglt_android@163.com
 * 类说明:便民服务中订阅更多栏目的界面
 * In me the tiger sniffs the rose
 */

public class ServiceSubscribeMoreActivity extends BaseActivity {

    Unbinder unbinder;

    private static final String TAG = "ServiceSubscribeMoreAct";

    @BindView(R.id.rv_tuijian)
    RecyclerView rv_tuijian;
    @BindView(R.id.rv_fuwufenlei)
    RecyclerView rv_fuwufenlei;
    @BindView(R.id.tv_title_bar)
    TextView tv_title_bar;
    @BindView(R.id.iv_back)
    ImageView iv_back;
    /**
     * 顶部列表适配器
     */
    private ServerSubscribeTopAdapter topAdapter;
    /**
     * 顶部数据集合
     */
    private List<ServerSubscribeRecomBean> topList = new ArrayList<>();

    String userName ;

    private ServerSubFeileiAdapter bottomAdapter;

    private List<CategoryBean> categoryBeanList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_service_subscribe_more);
        unbinder = ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        initView();
        initData();
    }

    /**
     * 初始化各个控件,主要是设置layoutManager还有设置adapter以及设置标题还有设置各个点击事件
     */
    private void initView() {

        tv_title_bar.setText("订阅服务");
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        rv_tuijian.setLayoutManager(new LinearLayoutManager(this));
        topAdapter = new ServerSubscribeTopAdapter(R.layout.item_service_recom_top,topList);
        rv_tuijian.setAdapter(topAdapter);
        rv_tuijian.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                Bundle bundle = new Bundle();
                bundle.putString("name",topList.get(position).getAppName());
                bundle.putString("url",topList.get(position).getAppMobileUrl());
                ActivityUtils.startActivity(bundle, ServiceAppDetailActivity.class);
            }
        });
        topAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.iv_recom_subscribe){
                    if (getIsLogin()){
                        if (topList.get(position).getRecommend().equals("1")){//当前为已订阅,执行取消订阅方法
                            cancleSub(topList.get(position).getAppUuid());
                        }else {//当前为未订阅,执行订阅方法
                            addSub(topList.get(position).getAppUuid());
                        }
                    }else {
                        toLogin();
                    }

                }
            }
        });

        rv_fuwufenlei.setLayoutManager(new GridLayoutManager(this,3,LinearLayoutManager.VERTICAL,false));
        rv_fuwufenlei.addItemDecoration(new SpaceItemDecoration(10));
        bottomAdapter = new ServerSubFeileiAdapter(R.layout.item_service_fuwu_fenlei,categoryBeanList);
        rv_fuwufenlei.setAdapter(bottomAdapter);
        rv_fuwufenlei.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                Bundle bundle = new Bundle();
                bundle.putString("name",categoryBeanList.get(position).getAppName());
                bundle.putString("serverKey",categoryBeanList.get(position).getCateId());
                ActivityUtils.startActivity(bundle, ServiceCatagoryListDetailsActivity.class);
            }
        });


    }

    private void initData() {
      getTopList();
      getBottomList();
    }

    private void getBottomList() {
        HttpMethods.getInstanceCenter().info.getServiceCategory()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ServiceCategoryBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(ServiceCategoryBean serviceCategoryBean) {
                        if (!categoryBeanList.isEmpty()){categoryBeanList.clear();}
                        if (null != serviceCategoryBean.getResult())
                        categoryBeanList.addAll(serviceCategoryBean.getResult());
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, "onError:获取服务列表失败 "+e.toString() );
                    }

                    @Override
                    public void onComplete() {
                        bottomAdapter.setNewData(categoryBeanList);
                        bottomAdapter.notifyDataSetChanged();
                    }
                });
    }

    /**
     * 获取顶部推荐栏目的数据方法
     */
    private void getTopList(){
        userName = activity.spUtils.getString(AppConstant.USER_UID);
        HttpMethods.getInstanceCenter().info.getServiceSubscribeRecomList(userName)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ServerSubscribeRecomNetBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(ServerSubscribeRecomNetBean serverSubscribeRecomNetBean) {
                        if (!topList.isEmpty()){topList.clear();}
                        if (null != serverSubscribeRecomNetBean.getResult())
                        topList.addAll(serverSubscribeRecomNetBean.getResult());
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, "onError:获取顶部失败 "+e.toString() );
                    }

                    @Override
                    public void onComplete() {
                        topAdapter.setNewData(topList);
                        topAdapter.notifyDataSetChanged();
                    }
                });
    }

    /**
     * 添加订阅
     * @param appUuid 服务项目的唯一标识
     */
    private void addSub(String appUuid){
        userName = activity.spUtils.getString(AppConstant.USER_UID);
        Log.e(TAG, "addSub: "+userName );
        HttpMethods.getInstanceCenter().info.addSub(userName,appUuid)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<UniversalBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(UniversalBean universalBean) {
                        Log.e(TAG, "onNext: 添加订阅"+universalBean.toString() );
                        if (universalBean.getMsg().equals("订阅成功")){
//                            ToastUtils.showShort("订阅成功");
                            ToastFactory.getToast(activity,"订阅成功").show();
                            getTopList();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, "onError:订阅失败 "+e.toString() );
                        ToastUtils.showShort("网络故障,订阅失败");
                    }

                    @Override
                    public void onComplete() {
                        EventBus.getDefault().post(new SubscribeChangeEvent("二级页面"));
                    }
                });

    }

    /**
     * 取消订阅
     * @param appUuid 服务栏目的唯一标识
     */
    private void cancleSub(String appUuid){
        userName = activity.spUtils.getString(AppConstant.USER_UID);
        HttpMethods.getInstanceCenter().info.cancleSub(userName,appUuid)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<UniversalBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(UniversalBean universalBean) {
                        Log.e(TAG, "onNext: 取消订阅"+universalBean.toString() );
                        if (universalBean.getMsg().equals("取消成功")){
//                            ToastUtils.showShort("取消订阅成功");
                            ToastFactory.getToast(activity,"取消订阅成功").show();
                            getTopList();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, "onError:取消订阅失败 "+e.toString() );
                        ToastUtils.showShort("网络故障,取消订阅失败");
                    }

                    @Override
                    public void onComplete() {
                        EventBus.getDefault().post(new SubscribeChangeEvent("二级页面"));
                    }
                });
    }

    @Subscribe
    public void onMessageEvent(SubscribeChangeEvent event) {
        Log.i(TAG, "message is " + event.getRefresh());
        // 更新界面
       if (ActivityUtils.isActivityExists("com.ln.lnzw","com.ln.lnzw.activity.ServiceSubscribeMoreActivity")){
           getTopList();
       }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        dispose();
        unbinder.unbind();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 判断是否已经登录,用token做依据
     * @return 用户是否已经登录
     */
    private boolean getIsLogin(){
        return !activity.spUtils.getString(AppConstant.TOKEN).isEmpty();
    }

    /**
     * 跳转登录页面,当用户未登录的时候跳转到登录页的方法
     */
    private void toLogin(){
        ActivityUtils.startActivity(activity, LoginActivity.class);
    }
}
